package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.hosp.repository.ScheduleRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.model.hosp.BookingRule;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.vo.hosp.BookingScheduleRuleVo;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class ScheduleServiceImpl implements ScheduleService {

    @Autowired
    private ScheduleRepository scheduleRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private HospitalService hospitalService;

    @Autowired
    private DepartmentService departmentService;


    //根据排班id获取预约下单数据
    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        //根据排班id得到排班数据
        Schedule schedule = this.getById(scheduleId);

        //根据排班数据得到医院对象
        Hospital hospital = hospitalService.findHospHoscode(schedule.getHoscode());
        //得到预约规则
        BookingRule bookingRule = hospital.getBookingRule();

        //scheduleOrderVo设置值
        scheduleOrderVo.setHoscode(schedule.getHoscode());
        scheduleOrderVo.setHosname(hospital.getHosname());
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        scheduleOrderVo.setDepname(departmentService.getDepartment(schedule.getHoscode(), schedule.getDepcode()).getDepname());
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        scheduleOrderVo.setTitle(schedule.getTitle());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        scheduleOrderVo.setAmount(schedule.getAmount());


        //退号截止天数（如：就诊前一天为-1，当天为0）
        int quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());

        //预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

        //预约截止时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());

        //当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStopTime(stopTime.toDate());

        return scheduleOrderVo;
    }


    //通过mq发来的信息跟新排班数据
    @Override
    public void updateSchdule(Schedule schedule) {
        schedule.setUpdateTime(new Date());
        scheduleRepository.save(schedule);
    }

    //通过id得到排班数据
    @Override
    public Schedule getById(String id) {
        Schedule schedule = scheduleRepository.findById(id).get();
        this.packagedSchedule(schedule);
        return schedule;
    }

    //显示科室预约日期数据（当前日期+预约周期）
    // 根据医院编号 + 科室编号查询 分页显示
    @Override
    public Map<String, Object> getBookingScheduleRule(Integer page, Integer limit, String hoscode, String depcode) {
        Hospital hospital = hospitalService.findHospHoscode(hoscode);
        if (hospital == null) {
            throw new YyghException(20001, "医院数据不存在");
        }
        BookingRule bookingRule = hospital.getBookingRule();
        //Integer cycle = bookingRule.getCycle();

        //获取可预约日期的分页数据
        IPage<Date> iPage = this.getListDate(page, limit, bookingRule);

        //每页显示日期数据集合
        List<Date> dateList = iPage.getRecords();

        //封装聚合条件
        Criteria criteria = Criteria.where("hoscode").is(hoscode)
                .and("depcode").is(depcode)
                .and("workDate").in(dateList);

        Aggregation aggregation = Aggregation.newAggregation(
                                        //匹配条件
                                        Aggregation.match(criteria)
                                        //分组 workdate
                                        , Aggregation.group("workDate")
                                        .first("workDate").as("workDate")
                                        .count().as("docCount")
                                        .sum("availableNumber").as("availableNumber")
                                        .sum("reservedNumber").as("reservedNumber")
        );

        //调用mongotemplate聚合查询
        AggregationResults<BookingScheduleRuleVo> aggregateResult =
                mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);

        List<BookingScheduleRuleVo> scheduleList = aggregateResult.getMappedResults();

        //根据所有显示日期，到查询集合比对是否有数据
        //有数据显示有号 没数据显示没号
        Map<Date, BookingScheduleRuleVo> scheduleVoMap = scheduleList.stream()
                .collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate,
                        BookingScheduleRuleVo -> BookingScheduleRuleVo));

        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        //
        for (int i = 0, len = dateList.size(); i < len; i++) {
            //每个日期
            Date date = dateList.get(i);

            //拿每个日期到map中比对 map的key是日期
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);
            if (bookingScheduleRuleVo == null) {
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                //无号，设置就诊医生人数
                bookingScheduleRuleVo.setDocCount(0);
                //设置剩余预约数 -1 = 无号
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }
            //设置日期
            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);


            //日期对应的星期
            String dayOfWeek = this.getDayOfWeek(new DateTime(date));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);


            //设置最后一天日期显示即将放号 （最后一页最后一条记录）
            //最后一页最后一条记录为即将预约
            // 状态  0：正常   1：即将放号    -1：当天已停止挂号
            if (i == len - 1 && page == iPage.getPages()) {// 最后一页 最后一条数据
                bookingScheduleRuleVo.setStatus(1);  //即将放号
            } else {
                bookingScheduleRuleVo.setStatus(0);
            }


            //判断第一页第一个日期（今天日期），今天日期时间是否过了停止挂号时间，如果过，显示停止挂号
            if (i == 0 & page == 1) {
                //获取今天停止挂号时间
                DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
                if (stopTime.isBeforeNow()) {
                    bookingScheduleRuleVo.setStatus(-1);
                }

    }
                //所有对象放到最终list集合
                bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }
        //4 返回需要数据
        Map<String, Object> result = new HashMap<>();
        //可预约日期集合数据
        result.put("bookingScheduleList", bookingScheduleRuleVoList);
        //总记录数
        result.put("total", iPage.getTotal());
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hosname", hospitalService.getHospName(hoscode));
        //科室
        Department department = departmentService.getDepartment(hoscode, depcode);
        //大科室名称
        baseMap.put("bigname", department.getBigname());
        //科室名称
        baseMap.put("depname", department.getDepname());
        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        //停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
        result.put("baseMap", baseMap);


        return result;

    }

    //根据医院编号 、科室编号和工作日期，查询排班详细信息
    @Override
    public List<Schedule> getScheduleDetail(String hoscode, String depcode, String workDate) {
        Date wordDateObj = new DateTime(workDate).toDate();
        List<Schedule> list = scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate(hoscode, depcode, wordDateObj);
        list.stream().forEach(item -> {
            this.packagedSchedule(item);
        });
        return list;
    }

    private Schedule packagedSchedule(Schedule schedule) {
        String hospName = hospitalService.getHospName(schedule.getHoscode());
        String deptName = departmentService.getDeptName(schedule.getHoscode(), schedule.getDepcode());

        schedule.getParam().put("hosname", hospName);
        schedule.getParam().put("depname", deptName);

        schedule.getParam().put("dayOfWeek", this.getDayOfWeek(new DateTime(schedule.getWorkDate())));
        return schedule;
    }

    //删除排班
    @Override
    public void remove(String hoscode, String hosScheduleId) {
        Schedule scheduleByHoscodeAndHosScheduleId = scheduleRepository.findScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);

        if (scheduleByHoscodeAndHosScheduleId != null) {
            scheduleRepository.deleteById(scheduleByHoscodeAndHosScheduleId.getId());
        }
    }


    //查询排班规则
    @Override
    public Map<String, Object> getScheduleRule(long page, long limit, String hoscode, String depcode) {
        //根据编号查询
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);
        Aggregation aggregation = Aggregation.newAggregation
                (Aggregation.match(criteria),
                        Aggregation.group("workDate")
                                .first("workDate").as("workDate")
                                .count().as("docCount")
                                .sum("reservedNumber").as("reservedNumber")
                                .sum("availableNumber").as("availableNumber"),
                        Aggregation.sort(Sort.Direction.ASC, "workDate"),
                        Aggregation.skip((page - 1) * limit),
                        Aggregation.limit(limit));


        AggregationResults<BookingScheduleRuleVo> aggregationResults = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggregationResults.getMappedResults();

        for (BookingScheduleRuleVo bookingScheduleRuleVo : bookingScheduleRuleVoList) {
            Date workDate = bookingScheduleRuleVo.getWorkDate();

            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        }
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );
        AggregationResults<BookingScheduleRuleVo> totalAggregate = mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> list = totalAggregate.getMappedResults();
        int total = list.size();

        Map<String, Object> result = new HashMap<>();
        result.put("bookingScheduleRuleVoList", bookingScheduleRuleVoList);
        result.put("total", total);

        String hospName = hospitalService.getHospName(hoscode);

        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname", hospName);
        result.put("baseMap", baseMap);

        return result;
    }

    //上传排班
    @Override
    public void saveSchedule(Map<String, Object> map) {
        String jsonString = JSONObject.toJSONString(map);
        Schedule schedule = JSONObject.parseObject(jsonString, Schedule.class);
        Schedule exist = scheduleRepository.findScheduleByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());
        if (exist != null) {
            schedule.setId(exist.getId());
            schedule.setUpdateTime(new Date());
            schedule.setStatus(exist.getStatus());
            schedule.setIsDeleted(exist.getIsDeleted());
            scheduleRepository.save(schedule);
        } else {
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            scheduleRepository.save(schedule);
        }
    }


    //分页
    @Override
    public Page<Schedule> selectPageSche(int page, int limit) {
        Sort sort = Sort.by(Sort.Direction.DESC, "creatTime");
        Pageable pageable = PageRequest.of(page - 1, limit, sort);

        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);

        Schedule schedule = new Schedule();
        Example<Schedule> example = Example.of(schedule, matcher);
        Page<Schedule> pages = scheduleRepository.findAll(example, pageable);
        return pages;
    }

    /**
     * 根据日期获取周几数据
     *
     * @param dateTime
     * @return
     */
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }

    /**
     * 获取可预约日期分页数据
     */
    private IPage<Date> getListDate(int page, int limit, BookingRule bookingRule) {
        //当天放号时间
        DateTime releaseTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        //预约周期
        int cycle = bookingRule.getCycle();
        //如果当天放号时间已过，则预约周期后一天为即将放号时间，周期加1
        if (releaseTime.isBeforeNow()) {
            //预约周期+1
            cycle += 1;
        }
        //可预约所有日期，最后一天显示即将放号倒计时
        List<Date> dateList = new ArrayList<>();
        for (int i = 0; i < cycle; i++) {
            //计算当前预约日期  把当前日期天数相加
            DateTime curDateTime = new DateTime().plusDays(i);
            String dateString = curDateTime.toString("yyyy-MM-dd");
            //把dateTime变成Date
            Date date = new DateTime(dateString).toDate();
            dateList.add(date);
        }
        //日期分页，由于预约周期不一样，页面一排最多显示7天数据，多了就要分页显示
        //4 分页显示
        //pageDateList为了分页显示集合
        List<Date> pageDateList = new ArrayList<>();

        //开始页 结束页
        int start = (page - 1) * limit;
        int end = (page - 1) * limit + limit;

        if (end > dateList.size()) end = dateList.size();
        for (int i = start; i < end; i++) {
            pageDateList.add(dateList.get(i));
        }

        IPage<Date> iPage =
                new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page, 7, dateList.size());
        //设置每页数据的list集合
        iPage.setRecords(pageDateList);
        return iPage;
    }


    /**
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     */
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " " + timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }
}
